import {
    useDispatch
} from "react-redux";
import store from "@/store";
import { renderMenuItem } from "@/routes";
import {matchPath, useLocation} from "react-router-dom";
import {useMemo} from "react";
//通用dispatch
type TDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<TDispatch>();//返回的是一个useDispatch()

//返回一级和二级标题
export const useAPPTitle = () => {
    const location = useLocation();
    return useMemo(() => {
        const path = "/"+location.pathname.split("/")[1];
        // 根据路由path找到路由信息
        const info = renderMenuItem().find((v:any)=>v.path === path);
        // 找到一级标题
        const title = info.label;
        // 找二级标题
        let subTitle;
        if (info.children) {
            // const subInfo = info.children.find((v: any) => v.path === location.pathname);
            //如果全等来判断，则路由地址携带参数就无法匹配 /hospitial/show  /hospitial/show/id(124554667)
            //采用matchPath来比较，如果路由不匹配，则返回空，匹配则返回一个对象
            //matchPath 有两个参数，第一个参数为路由地址，第二个参数为当前路径location.pathname
            //matchPath来自于react-router-dom
            const subInfo = info.children.find((v: any) => matchPath(v.path, location.pathname))
            // console.log(subInfo,'----+++')
            if (subInfo) subTitle = subInfo.label;
        }
        return {
            title,
            subTitle
        }
    },[location.pathname])
}